/**
 * @file userinfo
 * @author lishaohai
 */

import {SET_USER, SET_USER_TOKEN} from '@/store/mutation-types';
import router, {resetRouter} from '@/router/index';
import {LOGIN} from '@/router/route-name';
// 需要维护的状态
const state = {
    user: JSON.parse(localStorage.getItem(SET_USER) || '{}'), // 存储用户信息
    userToken: localStorage.getItem(SET_USER_TOKEN) || ''
};
const getters = {
    user: state => state.user,
    headers: state => ({Authorization: state.userToken})
};

const mutations = {
    // 设置用户token保存到store中
    setUserToken(state, value) {
        state.userToken = value;
        if (!value) {
            localStorage.removeItem(SET_USER_TOKEN);
        } else {
            localStorage.setItem(SET_USER_TOKEN, value);
        }
    },
    // 设置用户信息
    setUserInfo: (state, user) => {
        state.user = user;
        if (user) {
            localStorage.setItem(SET_USER, JSON.stringify(user || {}));
        } else {
            localStorage.removeItem(SET_USER);
        }
    }
};

const actions = {
    // 登出
    handleLogout({commit}) {
        // 重置路由
        resetRouter();
        // clear token
        commit('setUserToken', null);
        commit('setUserInfo', null);
        // 页面跳转
        router.push({name: LOGIN});
    }
};
export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};
